package ru.ifmo.trafficspy.analyzer.clustering;

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class KMeansClusterizer implements Clusterizer {
	private final double[] centers;
	public double maxDist;
	
	public KMeansClusterizer(double[] centers) {
		this.centers = new double[centers.length];
		double[] t = new double[centers.length];
		for (int i = 0; i < centers.length; i++) {
			this.centers[i] = centers[i];
			t[i] = centers[i];
		}
		Arrays.sort(t);
		double maxDist = (t[t.length - 1] - t[0]) / t.length;
		if (t.length == 1) {
			maxDist = Math.abs(t[0]) / 2;
		}
		for (int i = 1; i < t.length; i++) {
			maxDist = Math.max(maxDist, t[i] - t[i - 1]);
		}
		this.maxDist = maxDist;
	}
	
	public int getCluster(double value) {
		double minDist = Double.POSITIVE_INFINITY;
		int cluster = -1;
		for (int i = 0; i < centers.length; i++) {
			double curDist = Math.abs(centers[i] - value);
			if (curDist < minDist) {
				cluster = i;
				minDist = curDist;
			}
		}
		if (minDist > 2 * maxDist) {
			cluster = -1;
		}
		return cluster;
	}
	
	public void write(PrintWriter out) {
		out.println(centers.length);
		for (int i = 0; i < centers.length; i++) {
			out.print(centers[i] + " ");
		}
		out.println();
	}
	
	public static KMeansClusterizer read(Scanner in) {
		int n = in.nextInt();
		double[] centers = new double[n];
		for (int i = 0; i < n; i++) {
			centers[i] = in.nextDouble();
		}
		return new KMeansClusterizer(centers);
	}

	public int getClusterCount() {
		return centers.length;
	}
	
}
